import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getYueJiVenueSettings } from '../request.js';

/**
 * 月击网球（电商园校区）场地数据处理器
 */
export class YueJiDianShangYuanProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '月击网球（电商园校区）';
  }

  /**
   * 获取月击网球（电商园校区）场地预约设置
   * @param {Object} params - 查询参数 { date }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const defaultParams = {
      date: '2025-08-20'
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getYueJiVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
  validateData(data) {
    // 数据结构: {code: 0, data: {list: [], site_x: [], site_y: []}}
    return data && 
           data.data &&
           data.data.site_x && 
           Array.isArray(data.data.site_x) && 
           data.data.list && 
           Array.isArray(data.data.list);
  }

  /**
   * 按场地名称分组
   * @param {Object} data - 原始场地数据
   * @returns {Map} 场地Map
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 访问正确的数据路径: data.data.site_x
    data.data.site_x.forEach(site => {
      const venueName = site.site_name;
      if (!venueMap.has(venueName)) {
        venueMap.set(venueName, {
          name: venueName,
          siteId: site.site_id,
          timeSlots: []
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间槽
   * @param {Map} venueMap - 场地Map
   * @param {Object} data - 原始场地数据
   */
  processTimeSlots(venueMap, data) {
    venueMap.forEach((venue, venueName) => {
      // 遍历时间槽信息，访问正确的数据路径: data.data.list
      data.data.list.forEach(item => {
        if (item.site_name === venueName) {
          item.site_data.forEach(slot => {
            const timeSlot = `${slot.start_time.substring(0, 5)}-${slot.end_time.substring(0, 5)}`;
            const beginDatetime = `${this.selectedDate} ${slot.start_time}`;
            const endDatetime = `${this.selectedDate} ${slot.end_time}`;
            const price = slot.price;

            // 添加时间槽信息
            venue.timeSlots.push({
              time: timeSlot,
              isFree: slot.status === 2, // status=2表示可预约
              price: price== '999' ? 0 : price,
              beginDatetime: beginDatetime,
              endDatetime: endDatetime
            });
          });
        }
      });
    });
  }

  /**
   * 转换为场地列表
   * @param {Map} venueMap - 场地Map
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    return Array.from(venueMap.values()).map((venue, index) => {
      return {
        id: venue.siteId || (29000 + index), // 优先使用实际数据的siteId，否则使用默认ID
        name: venue.name,
        address: '月击网球（电商园校区）',
        latitude: 22.822158,
        longitude: 113.680577,
        phone: '0769-33445566',
        rating: 4.5,
        price: 0,
        facilities: ['室外场地', '专业教练'],
        image: '',
        distance: 23.5,
        timeSlots: venue.timeSlots,
        dataSource: this.venueName
      };
    });
  }
/**
   * 处理场地数据
   * @param {Object} data - 原始场地数据
   * @param {string} selectedDate - 选中的日期
   * @returns {Array} 处理后的场地列表
   */
  process(data, selectedDate) {
    if (!this.validateData(data)) {
      console.error('月击网球（电商园校区）数据验证失败');
      return [];
    }
    
    this.selectedDate = selectedDate;
    
    // 按场地名称分组
    const venues = this.groupVenues(data);
    
    // 处理时间槽
    this.processTimeSlots(venues, data);
    
    // 转换为场地列表
    return this.convertToVenueList(venues);
  }
}

export default YueJiDianShangYuanProcessor;